package Threads;

import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import de.greenrobot.event.EventBus;
import utils.HexUtil;
import utils.JX_Utils;
import xm.chengdu.com.beijing_211.MyEvent;
import xm.chengdu.com.beijing_211.Thread.YanZheng;

/**
 * 蓝牙通讯线程
 */
public class BluetoothCommunicateThread extends Thread {
    private static final int MAX_RECEIVE_DATA = 512;
    private static final long TIME_OUT = 2000;
    private Handler handler; // 与Service通信的Handler
    private BluetoothSocket socket;
    private InputStream inStream; // 对象输入流
    private OutputStream outStream; // 对象输出流
    StringBuffer buffer = new StringBuffer();
    StringBuffer buffer2;
    Boolean isshangban = true;
    String mingling;
    /**
     * false:停止运行
     */
    public static boolean isRun = false; // 运行标志位
    int nRet = 0;
    private byte[] recvBuffer = null;
    private byte[] sendBuffer = null;
    byte[] pBytesSend = null;
    int nLenTmp;
    private YanZheng resolveData = new YanZheng();

    String f6miyao;
    String init;
    int n = 2;
    int y = 0;

    Context context;


    // public static boolean isrun = false;

    public BluetoothCommunicateThread(Handler handler,
                                      BluetoothSocket bluetoothSocket, Context context) {
        // Log.e("88",
        // "88bluetooth socket=" + socket + ",isConnected="
        // + socket.isConnected());
        this.handler = handler;
        this.socket = bluetoothSocket;
        this.context = context;
        try {
            this.outStream = socket.getOutputStream();
            this.inStream = socket.getInputStream();

        } catch (Exception e) {
            try {
                socket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            // 发送连接失败消息
            // SendLoop.getExceptionMessage("Error连接失败,请重连");
            Message msg = new Message();
            msg.what = 2;
            handler.sendMessage(msg);

        }

    }

    @Override
    public void run() {
        super.run();
        recvBuffer = new byte[MAX_RECEIVE_DATA];
        while (true) {

            try {
                nLenTmp = inStream.read(recvBuffer);

                if (nLenTmp != -1) {
                    Log.e("77",
                            "nLenTmp"
                                    + HexUtil.BytesToString(recvBuffer, 0,
                                    nLenTmp));
                    nRet = resolveData.Analy55AA(recvBuffer, nLenTmp);
                    Log.e("77", "nRet" + nRet);

                    if (nRet == 0) {
//                        mingling = HexUtil.BytesToString(
//                                resolveData.getG_bytesRecv(), 0,
//                                resolveData.getZonglen2());
                        Log.e("77", "77收到完整数据帧:" + mingling);
                        Log.e("777", mingling);
                        sendMessage(mingling);
                        Message message = new Message();
                        message.what = 3;
                        message.obj = mingling;
                        handler.sendMessage(message);
                        switch (mingling.substring(10, 12)) {
                            //目标温度
                            case "A1":


                                break;
                            //   风速
                            case "A2":

                                break;
                            //多级角度
                            case "A3":

                                break;


                            //温度
                            case "A4":
                                int getzhi = getzhi(mingling);
                                MyEvent myEvent = new MyEvent();
                                myEvent.setType("A4");
                                myEvent.setJieguo(getzhi);
                                EventBus.getDefault().post(myEvent);
                                break;
                            //电流1
                            case "A5":
                                int getzhi2 = getzhi(mingling);
                                MyEvent myEvent2 = new MyEvent();
                                myEvent2.setType("A5");
                                myEvent2.setJieguo(getzhi2);
                                EventBus.getDefault().post(myEvent2);
                                break;
                            //电流2
                            case "A6":
                                int getzhi3 = getzhi(mingling);
                                MyEvent myEvent3 = new MyEvent();
                                myEvent3.setType("A6");
                                myEvent3.setJieguo(getzhi3);
                                EventBus.getDefault().post(myEvent3);
                                break;
                            //电压
                            case "A7":
                                int getzhi7 = getzhi(mingling);
                                MyEvent myEvent7 = new MyEvent();
                                myEvent7.setType("A7");
                                myEvent7.setJieguo(getzhi7);
                                EventBus.getDefault().post(myEvent7);
                                break;
                            default:
                                break;
                        }
//                        if (mingling.substring(10, 12).equals("F0")) {
//                            // 读手持机ID
//
//                        } else if (mingling.substring(8, 10).equals("F1")) {
//                            // 节点及费率信息下发
//                            String date = mingling.substring(10,
//                                    mingling.length() - 2);
////                            user = new Messages();
////                            user.setDesc(date);
////                            userDao.addSearch_Info(user);
//                            sendMessage("55AA0001E100E0");
//                            // 保存数据库
//                            // 55AA0001E100E0成功
//                            // 55AA0001E101E1 失败
//                        } else if (mingling.substring(8, 10).equals("F2")) {
//                            shujushangchuan();
//                            // 流水数据上传
//                            // 55AA0001E200E3 成功
//                            // 55AA0001E201E2 失败
//                        } else if (mingling.substring(8, 10).equals("F3")) {
//                            if (isshangban) {
//
//                            }
//                            // 员工上班
//                            shangban();
//                            n = 2;
//                            y = 0;
//                        } else if (mingling.substring(8, 10).equals("F4")) {
//                            // 员工下班
//                            xiaban();
//                            // 55AA0001E400E5 成功
//                            // 55AA0001E401E4 失败
//                        } else if (mingling.substring(8, 10).equals("F5")) {
//                            // 密钥更新请求
////                            huifuE5();
//                        } else if (mingling.substring(8, 10).equals("F6")) {
//                            f6miyao = mingling.substring(10,
//                                    mingling.length() - 10);
//                            String yanzheng = mingling.substring(
//                                    mingling.length() - 10,
//                                    mingling.length() - 2);
//
//                            // 后期改成动态的Rand
////                            String calDesMac = HexUtil
////                                    .CalDesMac("0102030400000000",
////                                            "00000000000000000000000000000000",
////                                            f6miyao);
////                            if (calDesMac.equals(yanzheng)) {
////                                sendMessage("55AA0001E600E7");
////                                Log.e("88", "55AA0001E600E7");
////                            } else {
////                                sendMessage("55AA0001E601E6");
////                                Log.e("88", "55AA0001E601E6");
////                            }
//                            // 密钥更新
//                            // 55AA0001E600E7 成功
//                            // 55AA0001E601E6 失败
//                        } else if (mingling.substring(8, 10).equals("F7")) {
//                            // 有效期更新请求
//
//                            String mess = HexUtil.GetRand(8);
//                            init = mess.substring(0, 8);
//                            String DATAS = "0001E700" + mess;
////                            String formt = Reponse.formt(DATAS);
////                            String E7ML = "55AA" + DATAS + formt;
////                            sendMessage(E7ML);
//                            // 55AA0001E700E6 成功
//                            // 55AA0001E701E7 失败
//                        } else if (mingling.substring(8, 10).equals("F8")) {
//                            String BCD = mingling.substring(10,
//                                    mingling.length() - 10);
//                            byte[] str2Bcd = HexUtil.str2Bcd(BCD);
//                            // BCD值 时间+有效期
//                            String vale = new String(str2Bcd);
//                            vale.substring(0, 14); // 时间
//                            vale.substring(14, vale.length());// 有效期
//                            Log.e("888", vale);
//                            // 55AA001AF8323031373032323230303030303032303137303332321507279B4D
////                            String jiemi = HexUtil.jiemi(f6miyao);
//                            // 有效期更新
////                            String calDesMac = HexUtil.CalDesMac(
////                                    "0102030400000000", jiemi, vale);
//                            String yanzheng = mingling.substring(
//                                    mingling.length() - 10,
//                                    mingling.length() - 2);
////                            if (calDesMac.equals(yanzheng)) {
////                                sendMessage("55AA0001E800E9");
////                                // Message msg = new Message();
////                                // msg.what = 3;
////                                // msg.obj = "tz";
////                                // handler.sendMessage(msg);
////                                Log.e("88", "55AA0001E800E9");
////                            } else {
////                                sendMessage("55AA0001E801E8");
////                            }
//                            // 55AA0001E800E9 成功
//                            // 55AA0001E801E8 失败
//                        } else if (mingling.substring(8, 10).equals("F9")) {
//                            // 删除数据
//                            // 55AA0001E900E8 成功
//                            // 55AA0001E901E9 失败
//
//                        }

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }


    public void sendMessage(byte[] b) {
        if (socket != null) {
            try {
                if (b.length > 0) {
                    outStream.write(b);
                }
                outStream.flush();
                Log.e("777", "7777");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMessage(String msg) {
        if (socket != null) {
            try {
                int datalen = msg.getBytes().length;
                int bytelen = 0;
                if ((datalen % 2) == 0)
                    bytelen = (int) (datalen / 2);
                else
                    bytelen = (int) (datalen / 2) + 1;

                sendBuffer = new byte[bytelen];
                int i = 0, j = 0;
                while (i < datalen) {
                    while (i >= 0 && (!CharInRange(msg.charAt(i))))
                        i++;

                    if (((i + 1) >= datalen)
                            || (!CharInRange(msg.charAt(i + 1)))) {
                        sendBuffer[j] = StrToByte(String.valueOf(msg.charAt(i)));
                        j++;
                    } else {
                        sendBuffer[j] = StrToByte(msg.substring(i, i + 2));
                        j++;
                    }

                    i += 2;
                }
                for (int m = 0; i < sendBuffer.length; m++) {
                    System.out.print(sendBuffer[m]);
                }
                outStream = new DataOutputStream(socket.getOutputStream());
                if (sendBuffer.length > 0) {
                    outStream.write(sendBuffer);
                }
                outStream.flush();
            } catch (Exception e) {
                Log.d("test", "--not connected 4--");
            }
        } else {
            Log.d("test", "--not connected 5--");
        }
    }

    private boolean CharInRange(char c) {
        boolean result = false;
        if (c >= '0' && c <= '9')
            result = true;
        if (c >= 'a' && c <= 'f')
            result = true;
        if (c >= 'A' && c <= 'F')
            result = true;
        return result;
    }

    private byte StrToByte(String s) {
        return Integer.valueOf(String.valueOf(Integer.parseInt(s, 16)))
                .byteValue();
    }


    public static int getzhi(String shi) {
        String substring = shi.substring(6, 10);
        int hexStringToInt = JX_Utils.hexStringToInt(substring);
        String substring2 = shi.substring(12, 12 + hexStringToInt * 2);
        int zong = JX_Utils.hexStringToInt(substring2);
        return zong;

    }

    public  void  close(){
        if (inStream!= null) {
            try {
                inStream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        if (outStream!= null) {
            try {
                outStream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } }
}
